import os
import json
import datetime
from config.config import REPORT_DIR, REPORT_TITLE


class ReportGenerator:
    def __init__(self, test_results, test_start_time, test_end_time):
        self.test_results = test_results
        self.test_start_time = test_start_time
        self.test_end_time = test_end_time

        # 读取模板文件
        template_path = os.path.join('templates', 'report_template.html')
        with open(template_path, 'r', encoding='utf-8') as f:
            self.template = f.read()  # 不使用 Template 类

        # 读取CSS文件
        css_path = os.path.join('templates', 'css', 'report_style.css')
        with open(css_path, 'r', encoding='utf-8') as f:
            self.css = f.read()

    def generate_report(self):
        # 准备数据
        data = self._prepare_report_data()

        # 替换模板中的变量
        html_content = self.template.format(**data)

        # 保存报告
        timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
        report_file = os.path.join(REPORT_DIR, f'test_report_{timestamp}.html')

        with open(report_file, 'w', encoding='utf-8') as f:
            f.write(html_content)

        return report_file

    def _prepare_report_data(self):
        # 计算测试结果统计
        total_cases = len(set(result['测试用例编号'] for result in self.test_results))
        passed_cases = len(set(result['测试用例编号'] for result in self.test_results
                               if result['执行结果'] == 'Pass'))
        failed_cases = total_cases - passed_cases
        pass_rate = (passed_cases / total_cases * 100) if total_cases > 0 else 0

        # 计算总执行时间
        if self.test_results:
            total_duration = self.test_end_time - self.test_start_time
        else:
            total_duration = datetime.timedelta(0)

        # 修改步骤标签生成逻辑
        step_labels = []
        step_durations = []
        current_case = None
        case_count = 0

        for step in self.test_results:
            # 当遇到新的测试用例时，增加计数
            if current_case != step['测试用例编号']:
                current_case = step['测试用例编号']
                case_count += 1

            # 生成包含用例编号的步骤标签
            label = f"用例{case_count}-步骤{step['步骤编号']}"
            step_labels.append(label)
            step_durations.append(step['执行时长'].total_seconds())

        return {
            'title': REPORT_TITLE,
            'test_time': self.test_start_time.strftime('%Y-%m-%d %H:%M:%S'),
            'total_duration': f"{total_duration.total_seconds():.2f}",
            'total_cases': total_cases,
            'pass_rate': f"{pass_rate:.1f}",
            'passed_cases': passed_cases,
            'failed_cases': failed_cases,
            'case_step_labels': json.dumps(step_labels),  # 修改变量名以匹配模板
            'step_durations': json.dumps(step_durations),
            'test_cases_content': self._generate_test_cases_content(),
            'css': self.css
        }

    def _generate_test_cases_content(self):
        content = ""
        current_case = None

        for step in self.test_results:
            if current_case != step['测试用例编号']:
                if current_case is not None:
                    content += '</div>'
                current_case = step['测试用例编号']
                content += f'''
                    <div class="test-case">
                        <h3>测试用例: {current_case}</h3>
                '''

            result_class = 'pass' if step['执行结果'] == 'Pass' else 'fail'
            content += f'''
                <div class="test-step">
                    <h4>步骤 {step['步骤编号']}: {step['测试步骤']}</h4>
                    <span class="status-badge status-{result_class}">{step['执行结果']}</span>
                    <div class="step-timing">
                        <p>开始时间: {step['开始时间'].strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]}</p>
                        <p>结束时间: {step['结束时间'].strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]}</p>
                        <p>执行时长: {step['执行时长'].total_seconds():.3f} 秒</p>
                    </div>
            '''

            if step.get('错误信息'):
                content += f'''
                    <div class="error-message">
                        <p>错误信息: {step['错误信息']}</p>
                    </div>
                '''

            if step.get('截图'):
                content += f'''
                    <div class="screenshot-container">
                        <img class="screenshot" src="{step['截图']}" alt="测试截图" onclick="showImage(this.src)">
                    </div>
                '''

            content += '</div>'

        if current_case is not None:
            content += '</div>'

        return content
